<script setup lang="ts">
import { reactive, ref, onMounted, watch } from "vue";
import { uploadPictureURL } from "@/api";
import { useToken } from "@/stores/token";
import { getCategoryList, addGoods, updateGoods } from "@/api";
import type { AxiosResponse } from "axios";
import type { FormInstance, UploadInstance } from "element-plus";
import type { Category } from "@/model";
import { ElMessage } from "element-plus";
import CKEditor from "./CKEditor.vue";
const emit = defineEmits(["closeDialog"]);
const props = defineProps(["isShow", "goods"]);
const tokenStore = useToken();
const uploadURL = uploadPictureURL();
const headers = { jwt: tokenStore.token };
const formObj = reactive({
  name: "",
  category_id: "",
  price: "",
  picture: "",
  stock: "",
  spec: "",
  description: "",
});
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();
const fileList = ref();
const categoryList = ref<Category[]>();
const rules = reactive({
  name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  category_id: [
    { required: true, message: "分类名称不能为空", trigger: "blur" },
  ],
  price: [
    { required: true, message: "商品价格不能为空", trigger: "blur" },
    { type: "number", message: "商品价格必须是数字类型", trigger: "blur" },
  ],
  picture: [{ required: true, message: "商品图片不能为空", trigger: "blur" }],
  stock: [
    { required: true, message: "商品库存不能为空", trigger: "blur" },
    { type: "number", message: "商品库存必须是数字类型", trigger: "blur" },
  ],
  spec: [{ required: true, message: "商品规格不能为空", trigger: "blur" }],
  description: [
    { required: true, message: "商品简介不能为空", trigger: "blur" },
  ],
});
async function submitForm() {
  await formRef.value?.validate(async (valid, _fields) => {
    if (valid) {
      var res = null;
      if (props.goods.id == 0) {
        res = await addGoods(formObj);
      } else {
        const data = {
          id: props.goods.id,
          name: formObj.name,
          category_id: formObj.category_id,
          price: formObj.price,
          picture: formObj.picture.substring(
            formObj.picture.lastIndexOf("static")
          ),
          stock: formObj.stock,
          spec: formObj.spec,
          description: formObj.description,
          album: [],
        };
        res = await updateGoods(data);
      }
      if (res.data.errno == 0) {
        emit("closeDialog");
        ElMessage.success(res.data.errmsg);
      } else {
        ElMessage.error(res.data.errmsg);
      }
    }
  });
}
function uploadSuccess(response: AxiosResponse) {
  formObj.picture = response.data.savepath;
}
function removeSuccess() {
  formObj.picture = "";
}
async function loadCategoryList() {
  const res = await getCategoryList();
  convertToTree(res.data.data);
}
function convertToTree(data: Category[]) {
  var newData: Category[] = [];
  data.forEach((v) => {
    if (v.pid == 0) {
      newData.push(v);
    }
  });
  newData.forEach((v) => {
    const result = data.filter((item) => item.pid == v.id);
    v.children = result;
  });
  categoryList.value = newData;
}
function initForm() {
  if (props.goods.id != 0) {
    formObj.name = props.goods.name;
    formObj.category_id = props.goods.category_id;
    formObj.price = props.goods.price;
    formObj.picture = props.goods.picture;
    formObj.stock = props.goods.stock;
    formObj.spec = props.goods.spec;
    formObj.description = props.goods.description;
    fileList.value = [
      {
        name: props.goods.picture.substring(
          props.goods.picture.lastIndexOf("/") + 1
        ),
        url: props.goods.picture,
      },
    ];
  } else {
    formObj.name = "";
    formObj.category_id = "";
    formObj.price = "";
    formObj.picture = "";
    formObj.stock = "";
    formObj.spec = "";
    formObj.description = "";
    uploadRef.value?.clearFiles();
  }
}
watch(props, () => {
  initForm();
});
onMounted(() => {
  loadCategoryList();
  initForm();
});
</script>

<template>
  <el-form
    ref="formRef"
    :model="formObj"
    :rules="rules"
    label-width="120"
    status-icon
  >
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formObj.name"
        placeholder="请填写商品名称"
        style="width: 500px"
      ></el-input>
    </el-form-item>
    <el-form-item label="分类名称" prop="category_id">
      <el-select
        v-model="formObj.category_id"
        placeholder="请选择二级分类名称"
        style="width: 200px"
      >
        <el-option-group v-for="group in categoryList" :label="group.name">
          <el-option
            v-for="item in group.children"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-option-group>
      </el-select>
    </el-form-item>
    <el-form-item label="商品价格" prop="price">
      <el-input
        v-model.number="formObj.price"
        placeholder="请填写商品价格"
        style="width: 500px"
      ></el-input>
    </el-form-item>
    <el-form-item label="商品图片" prop="picture">
      <el-upload
        ref="uploadRef"
        :action="uploadURL"
        v-model:file-list="fileList"
        :limit="1"
        :headers="headers"
        :data="{ type: 'goods' }"
        :on-success="uploadSuccess"
        :on-remove="removeSuccess"
      >
        <template #trigger>
          <el-button type="primary">选择图片</el-button>
        </template>
        <template #tip>
          <div class="upload_tooltip">图片文件大小不超过500KB</div>
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品库存" prop="stock">
      <el-input
        v-model.number="formObj.stock"
        placeholder="请填写库存数量"
        style="width: 500px"
      ></el-input>
    </el-form-item>
    <el-form-item label="商品规格" prop="spec">
      <el-input
        v-model="formObj.spec"
        placeholder="请填写商品规格"
        style="width: 500px"
      ></el-input>
    </el-form-item>
    <el-form-item label="商品简介" prop="description">
      <div class="editor-box">
        <CKEditor v-model="formObj.description"></CKEditor>
      </div>
    </el-form-item>
    <el-form-item label="">
      <el-button type="primary" @click="submitForm">{{
        props.goods.id == 0 ? "新增" : "修改"
      }}</el-button>
      <el-button @click="initForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.upload_tooltip {
  font-size: 13px;
  color: #a8abb2;
}
.editor-box {
  width: 500px;
}
</style>
